<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="外包公司名称">
                <a-input v-model="queryParam.name" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
                <a-form-item label="外包公司等级">
                  <!-- <a-input v-model="queryParam.name" placeholder="" /> -->
                  <a-select v-model="queryParam.type" placeholder="请选择">
                    <a-select-option v-for="it in levelArr" :key="it.id" :value="it.id">{{ it.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            <template v-if="advanced">
              <a-form-item label="地区">
                <a-cascader 
                  v-model="queryParam.address"
                  :options="cityArr" 
                  placeholder="地区"  
                  :fieldNames="{label:'name',children:'children',value:'name'}"/>
              </a-form-item>
            </template>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  @click="() => ((this.queryParam = {}), this.$refs.table.refresh(true))"
                  >重置</a-button
                >
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:epiboly_add>新建</a-button>
      </div>

      <s-table ref="table" size="default" rowKey="id" :columns="columns" :data="loadData" showPagination="auto" :scroll="{ x: true }">
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:epiboly_update>编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)" v-action:epiboly_update>删除</a>
          </template>
        </span>
        <span slot="amount" slot-scope="text, record" style="font-size:13px;">
          <div>(项目款) : ￥{{record.totalAmount || '0'}}</div>
          <div>(已付款) : ￥{{record.alreadyAmount || '0'}}</div>
          <div style="color:red;">(逾期) : ￥{{record.delayAmount || '0'}}</div>
        </span>
        <span slot="address" slot-scope="text,scope">
          <span>{{`${scope.country}-${scope.province}-${scope.city}`}}</span>
        </span>
        <span slot="adminList" slot-scope="text,scope">
          <div v-for="it in scope.adminList" :key="it.id">{{it}}</div>
        </span>
        <span slot="teamUser" slot-scope="text,scope">
          <span>{{scope}}</span>
        </span>
        
      </s-table>
      <epiboly-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :levelArr="levelArr"
        :country="country"
        :provinceArr="provinceArr"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <!-- <step-by-step-modal ref="modal" @ok="handleOk" /> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment';
import cloneDeep from 'lodash.clonedeep'
import { STable, Ellipsis } from '@/components'
import { epibolyAdd, epibolyList, epibolyUpdate } from '@/api/system'
import { levelListByNoAuth } from '@/api/noAuth'
import EpibolyForm from './modules/epibolyForm'
import { colors, eachMap } from '@/utils/other'
import { provinceArr } from '@/utils/ccity'
import { country } from '@/utils/country'
import { cityArr } from '@/utils/ccity'
import { Cascader } from 'ant-design-vue'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    fixed: true,
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    fixed: true,
  },
  {
    title: '款项',
    dataIndex: 'amount',
    scopedSlots: { customRender: 'amount' },
  },
  {
    title: '地区',
    dataIndex: 'city',
    width: '180px',
    scopedSlots: { customRender: 'address' },
  },
  {
    title: '级别',
    dataIndex: 'levelName',
    sorter: true,
    key: 'levelName',
  },
  {
    title: '描述',
    dataIndex: 'remark',
    key: 'remark',
  },
  {
    title: '人数',
    dataIndex: 'teamUser',
    key: 'teamUser',
  },
  // {
  //   title: '项目(总/已完成/进行中/超时)',
  //   dataIndex: 'projectNum',
  //   sorter: true,
  //   key: 'projectNum',
  // },
  {
    title: '负责人',
    dataIndex: 'contactName',
    key: 'contactName',
  },
  {
    title: '负责人号码',
    dataIndex: 'contactPhone',
    key: 'contactPhone',
  },
  // {
  //   title: '技术负责人',
  //   dataIndex: 'teamUser',
  //   key: 'teamUser',
  // },
  {
    title: '添加人',
    dataIndex: 'addUserName',
    key: 'addUserName',
    customRender: (text) => text || '--',
  },
  {
    title: '添加时间',
    dataIndex: 'addTime',
    key: 'addTime',
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑人',
    dataIndex: 'lastUpdateUserName',
    key: 'lastUpdateUserName',
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑时间',
    dataIndex: 'lastUpdateTime',
    key: 'lastUpdateTime',
    customRender: (text) => text || '--',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]

let countryArr = country.map(v=>{
  return {
    name:v.chinese_name
  }
})

export default {
  name: 'AMW-EpibolyList',
  components: {
    STable,
    Ellipsis,
    EpibolyForm,
    'a-cascader': Cascader,
  },
  data() {
    this.columns = columns
    return {
      cityArr,
      provinceArr:provinceArr,
      country:countryArr,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      levelArr: [],
      queryParam: {
      },
      data: [],
      sortJ: {
        levelNum: 'level_num',
        teamUser: 'team_user',
        projectNum: 'project_num',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        console.log(parameter)
        let sortJ = this.sortJ
        if (parameter.sortField) {
          parameter.sortJ = sortJ
        }
        let queryParam = cloneDeep(this.queryParam)
        let { address } = queryParam
        console.log(address)
        console.log(parameter)
        if(address){
          queryParam.country = address[0]
          queryParam.province = address[1]
          queryParam.city = address[2]
          delete queryParam.address
        }
        
        const requestParameters = Object.assign({}, parameter, queryParam)
        // let data = {"pageNum":1,"pageSize":10}
        console.log('loadData request parameters:', requestParameters)
        return epibolyList(requestParameters).then((res) => {
          console.log(res, 'res')
          let result = {
            data: res.data.data,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },

  created() {
    // let query = this.$route.query
    // this.queryParam = {...this.queryParam, ...query}
    this.getLevel()
    // getRoleList({ t: new Date() })
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
    c_cityArr:function(){
      let provinceArr = cloneDeep(this.provinceArr)
      let queryParam = cloneDeep(this.queryParam)
      if(queryParam.province){
        let i = provinceArr.findIndex(v=>v.name == queryParam.province)
        console.log(provinceArr[i])
        return provinceArr[i].cityList
      }else{
        return []
      }
    }
  },
  methods: {
    getLevel() {
      levelListByNoAuth({ pageNum: 1, pageSize: 10, type: 4 }).then((res) => {
        console.log(res)
        this.levelArr = res.data.data
      })
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if(values.address){
            values.country = values.address[0]
            values.province = values.address[1]
            values.city = values.address[2]
            delete values.address
          }
          if (values.id > 0) {
            epibolyUpdate(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('修改成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          } else {
            delete values.id
            epibolyAdd(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('新增成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleDel(a_record) {
      let self = this
      const modal = this.$confirm({
        title: '外包公司删除',
        content: `是否删除外包公司:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDelete(a_record.id, modal),
        onCancel: () => {},
      })
    },
    handleDelete(a_id, a_modal) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: -1 }
        studioUpdate(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
  },
}
</script>

 